<template>
  <view class="offlineMain" :style="offlineMainStyle">
    <view class="dateTitle flex alignCenter fz14 bold">
      <uv-image src="https://meet-city.oss-cn-beijing.aliyuncs.com/images/2024/10/18/1729265200720578.png" width="18px" height="18px"></uv-image>
      <text>我参加的活动</text>
    </view>

    <scroll-view scroll-x>
      <view class="dates flex">
        <view class="date shrink textCenter" @click="dateClick(index)" :class="{active:dateCurrent==index}" v-for="(item,index) in dates" :key="index">
          <view class="h fz14 bold">{{proxy.$utils.dateTimeFormateFn(item,'monthDate')}}</view>
          <view class="p fz12">{{week_Format(item)}}</view>
        </view>
      </view>
    </scroll-view>

    <view class="tabs flex alignCenter">
      <view class="item flex alignCenter fz14" :class="{active:current==index}" @click="tabClick(index)" v-for="(item,index) in tabs" :key="index">
        <uv-image v-if="current==index" src="https://meet-city.oss-cn-beijing.aliyuncs.com/images/2024/10/20/17293555424993539.png" width="14px" height="14px"></uv-image>
        <view class="name">{{item.name}}</view>
      </view>
    </view>

    <!-- 活动日历 -->
    <view v-if="current==2">
      <view class="fz18 bold" @click="instance.refs.datetimePickerRef.open()" style="margin-bottom: 15px;">{{proxy.$utils.dateTimeFormateFn(currentData,'month')}}-{{proxy.$utils.p(timeDataCurrent+1)}} {{week_Format(selectDate)}}</view>

      <scroll-view scroll-x :scroll-left="scrollLeft">
        <view class="months flex">
          <view class="item shrink textCenter" :id="`month${index}`" @click="monthClick(index)" :class="{active:timeDataCurrent==index}" v-for="(item,index) in months" :key="index">
            <view class="bold fz16">{{proxy.$utils.dateTimeFormateFn(item,"day")}}</view>
            <view class="p fz12">{{week_Format(item)}}</view>
          </view>
        </view>
      </scroll-view>

      <datetimePicker v-model="selectDate" mode="date" placeholder="请选择" ref="datetimePickerRef"></datetimePicker>
    </view>

    <!-- 热门活动 -->
    <view class="hotActivity" v-if="current==0">
      <view class="firstBox" @click="proxy.$utils.toLink(`/packagePages/activity/details?activityId=${topActivity.activityId}`)">
        <view class="banner positionRelative">
          <image :src="topActivity.activityImageUrl" mode="widthFix" />
          <view class="day">{{topActivity.activityStartTime}}</view>
          <view class="isVip" v-if="topActivity.isVipActivity">
            <uv-image src="https://meet-city.oss-cn-beijing.aliyuncs.com/images/2024/10/20/17294262813174292.png" width="62px" height="20px"></uv-image>
          </view>
        </view>
        <view class="data">
          <view class="title fz16 bold">{{topActivity.activityName}}</view>
          <view class="desc fz14">{{topActivity.toppedIntroduction}}</view>
          <view class="flex justifyBetween alignCenter">
            <view class="flex alignCenter">
              <uv-avatar-group :urls="topActivity.participantLogos" size="35" gap="0.6"></uv-avatar-group>
              <view class="join fz14" v-if="topActivity.isRegister==0">参加</view>
            </view>
            <uv-button text="立即报名" v-if="topActivity.isRegister==0" color="#FEEFF4" shape="circle" customTextStyle="color:#F2628D" customColor="#FEEFF4"></uv-button>
          </view>
        </view>
      </view>
    </view>

    <activityItem v-for="(item,index) in list" :key="index" :item="item"></activityItem>
    <uv-load-more :status="status" v-if="list.length" />

    <view v-if="list.length==0" style="margin-top: 30px;">
      <uv-empty mode="data" text="暂无活动"></uv-empty>
    </view>

  </view>
</template>

<script setup lang="ts">
import datetimePicker from "@/components/uv/datetimePicker.vue";
import activityItem from "@/pages/tabbar/tabbar-1/components/activityItem.vue";
let props = defineProps(["info", "navHeight"]);
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();
const instance = getCurrentInstance();

//1-立即报名(上架) 2-已报名 3-已结束 4-下架活动
let tabs = ref([
  { name: "热门活动", value: 1 },
  { name: "精彩回顾", value: 3 },
  { name: "活动日历", value: 1 },
]);
let loading = ref(false);
let scrollLeft = ref(0);
let currentData = ref(new Date());
let params = {
  page: 1,
  pageSize: 10,
  date: "",
  province: "北京市",
  status: 1,
};
let total = ref(0); //总数
let list = ref([]);
let current = ref(0); //tabs的索引
let dateCurrent = ref(0); //日期索引
let timeDataCurrent = ref(0);
let topActivity = ref({});
let status = ref("loadmore");
let selectDate = ref("");

//选中的日期
let selectMonthDate = computed(() => {
  return `${proxy.$utils.dateTimeFormateFn(
    currentData.value,
    "yearMonth"
  )}-${proxy.$utils.p(timeDataCurrent.value + 1)}`;
});

let offlineMainStyle = computed(() => {
  return {
    marginTop: `${counter.navBarHeight + 15}px`,
  };
});

//本月日期
let months = computed(() => {
  let firstDay = proxy.$utils.getCurrentMonthFirst(currentData.value);
  let lastDay = proxy.$utils.getCurrentMonthLast(currentData.value);
  let days = proxy.$utils.getdiffdate(firstDay, lastDay);
  return days;
});

// 本周日期
let dates = computed(() => {
  let date = new Date();
  function getDatesOfCurrentWeek(date) {
    let current = new Date(date);
    let dayOfWeek = current.getDay() || 7; // 使周日的值为7
    let start = current.getDate() - dayOfWeek + 1; // 计算周一的日期
    let dates = [];

    for (let i = 0; i < 7; i++) {
      let date = new Date(current);
      date.setDate(start + i);
      dates.push(proxy.$utils.dateTimeFormateFn(new Date(date)));
    }
    return dates;
  }
  return getDatesOfCurrentWeek(date);
});

onMounted(() => {
  getInfo();
  getTopActivity();
});

function getMore() {
  if (list.value.length >= total) return;
  params.page++;
  getInfo();
}

//获取页面元素信息
function viewInfo(id, type) {
  return new Promise((resolve, reject) => {
    uni
      .createSelectorQuery()
      .in(instance)
      .select(id)
      .boundingClientRect((data) => {
        if (data) {
          resolve(data[type]);
        } else {
          resolve(0);
        }
      })
      .exec();
  });
}

function dateClick(index) {
  dateCurrent.value = index;
  proxy.$utils.toLink("/packagePages/activity/myJoinActivities");
}

function monthClick(index) {
  timeDataCurrent.value = index;
  params.date = proxy.$utils.dateTimeFormateFn(
    months.value[index],
    "monthDate"
  );
  list.value = [];
  params.page = 1;
  getInfo();
}

async function getTopActivity() {
  topActivity.value = await proxy.$apis.getTopActivity({ province: "北京市" });
  console.log("指定活动", topActivity.value);
}

function removeLeadingZero(str) {
  if (str.startsWith("0")) {
    return str.slice(1);
  }
  return str;
}

function tabClick(index) {
  current.value = index;
  params.status = tabs.value[index].value;
  if (index == 2) {
    if (timeDataCurrent.value == 0) {
      let today = proxy.$utils.dateTimeFormateFn(new Date(), "day");
      today = removeLeadingZero(today);
      timeDataCurrent.value = Number(today) - 1;
    }
    params.date = proxy.$utils.dateTimeFormateFn(
      months.value[timeDataCurrent.value],
      "monthDate"
    );
  } else {
    params.date = "";
  }
  nextTick(async () => {
    let left = await viewInfo(`#month${timeDataCurrent.value}`, "left");
    scrollLeft.value = Number(left) - 50 <= 0 ? 0 : Number(left) - 50;
  });

  init();
}

function week_Format(date) {
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  const weekday = new Date(date).getDay();
  return weekdays[weekday];
}

let init = () => {
  list.value = [];
  params.page = 1;
  getInfo();
};

let tabsClick = (item) => {
  current.value = item.index;
  params.status = tabs.value[item.index].value;
  init();
};

let getInfo = async () => {
  try {
    status.value = "loading";
    let resp = await proxy.$apis.activity(params);
    let arr = [...list.value];
    if (resp.records.length) {
      arr.push(...resp.records);
    }
    total = resp.total;
    list.value = proxy.$utils.arrayUnique2(arr, "activityId");
  } catch (error) {
  } finally {
    status.value = "nomore";
  }
};

let loadMore = () => {
  if (list.value.length >= total) return;
  params.page++;
  getInfo();
};

watch(
  () => selectMonthDate.value,
  (newValue, oldValue) => {
    if (newValue) selectDate.value = newValue;
  },
  { deep: true, immediate: true }
);

watch(
  () => selectDate.value,
  (newValue, oldValue) => {
    if (newValue) {
      let day = proxy.$utils.dateTimeFormateFn(newValue, "day");
      day = removeLeadingZero(day);
      timeDataCurrent.value = Number(day) - 1;
      currentData.value = new Date(newValue);
    }
  },
  { deep: true, immediate: true }
);

defineExpose({ getMore });
</script>



<style lang="scss" scoped>
.offlineMain {
  padding: 0 15px;
  .dateTitle {
    color: #000000;
    margin-bottom: 15px;
    text {
      margin-left: 7px;
    }
  }
  .dates {
    .active {
      background-color: #00d4ff;
      color: white;
      border-radius: 20px;
      .p {
        color: white !important;
      }
    }
    .date {
      margin-right: 15px;
      padding: 10px 5px;
      .p {
        color: #8f9bb3;
        margin-top: 5px;
      }
    }
  }
  .tabs {
    margin: 15px 0;
    .active {
      color: white;
      background-color: #36d9fa !important;
      border: 1px solid #b9f3ff !important;
    }
    .item {
      margin-right: 15px;
      background-color: #f8f7f0;
      border: 1px solid #e3e2de;
      border-radius: 15px;
      padding: 5px 10px;
      .name {
        margin-left: 5px;
      }
    }
  }
  .hotActivity {
    .banner {
      image {
        display: block;
        width: 100%;
      }
    }
    .day {
      position: absolute;
      background-color: rgba(17, 201, 189, 0.66);
      right: 15px;
      top: 0;
      color: white;
      font-size: 14px;
      font-weight: bold;
      padding: 10px;
      border-radius: 0 0 25px 25px;
    }
    .firstBox {
      .isVip {
        position: absolute;
        left: 5px;
        top: 5px;
      }
      .data {
        background-color: white;
        padding: 10px 15px;
        border-radius: 0 0 15px 15px;
        .title {
          color: #363d4e;
        }
        .desc {
          padding: 5px 0;
          color: #4f4b66;
        }
        .join {
          color: #13c9bd;
          margin-left: 12px;
        }
      }
    }
  }
  .months {
    .active {
      background-color: #c5f4fa !important;
      border: 1px solid #00d4ff !important;
      color: #00d4ff;
      .p {
        color: #00d4ff !important;
      }
    }
    .item {
      background: white;
      border: 1px solid #eceff2;
      border-radius: 10px;
      padding: 10px;
      margin-right: 15px;
      .p {
        margin-top: 5px;
        color: #a0aec0;
      }
    }
  }
}
</style>
